package com.jiangnan.viewmodel

import androidx.lifecycle.LiveData
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.jiangnan.entity.Book
import com.jiangnan.entity.Res
import com.jiangnan.repository.BookRepository
import com.jiangnan.util.CurrentHolder
import com.jiangnan.util.CurrentLoginInfo
import com.jiangnan.util.EventUtil
import kotlinx.coroutines.launch
import okhttp3.MultipartBody

class BookViewModel : ViewModel() {

    private val TAG = "BookViewModel"

    private val repository = BookRepository()


    // 扫描结果（库存书籍）
    private var _bookList = MutableLiveData<MutableList<Book>?>()
    val bookList: LiveData<MutableList<Book>?> = _bookList

    private var _total = MutableLiveData<Long>()
    val total: LiveData<Long> = _total

    private var _toastMessage  = MutableLiveData<EventUtil<String>>()
    val toastMessage : LiveData<EventUtil<String>> = _toastMessage

    // 新增借阅接口的 LiveData，用于返回借阅结果
    private var _borrowResponse = MutableLiveData<Res<String>>()
    val borrowResponse: LiveData<Res<String>> = _borrowResponse

    // 用于查询借阅图书列表的 LiveData
    private val _borrowedBooks = MutableLiveData<List<Book>>()
    val borrowedBooks: LiveData<List<Book>> = _borrowedBooks

    // 还书接口返回结果
    private val _returnResponse = MutableLiveData<Res<String>>()
    val returnResponse: LiveData<Res<String>> = _returnResponse

    // 借阅接口的 LiveData，用于返回借阅结果 QRCode
    private var _qrcodeResponse = MutableLiveData<Res<String>>()
    val qrcodeResponse: LiveData<Res<String>> = _qrcodeResponse

    private val _allBorrowedBooks = MutableLiveData<List<Book>>()
    val allBorrowedBooks: LiveData<List<Book>> = _allBorrowedBooks

    private val _allReturnedBooks = MutableLiveData<List<Book>>()
    val allReturnedBooks: LiveData<List<Book>> = _allReturnedBooks


    /**
     * 根据条件获取所有的图书信息
     */
    fun getAllBooks(page : Int?, pageSize : Int?, requestParam : String?){
        try {
            viewModelScope.launch {
                val response = repository.getAllBooks(page, pageSize, requestParam)
                if (response.code == 1) {
                    if (page == 1){
                        _bookList.postValue(response.data?.rows)
                    }else{
                        val currentList = _bookList.value ?: mutableListOf()
                        // 仅追加新获取的 21 条数据
                        response.data?.rows?.let { newList ->
                            currentList.addAll(newList)
                            _bookList.postValue(currentList)
                        }
                    }
                    _total.value = response.data?.total!!.toLong() ?: 0L
                    _toastMessage.postValue(EventUtil("库存信息获取成功"))
//                    _toastMessage.postValue(EventUtil(total.value.toString()))
                } else {
                    _bookList.postValue(null)
                    _total.postValue(0L)
                    _toastMessage.postValue(EventUtil("库存信息获取失败，请检查网络"))
                }
            }
        } catch (e: Exception) {
            e.printStackTrace()
        }
    }

    /**
     * 根据条件获取所有的图书信息
     */
    fun getAllBooksOrderByBorrowNum(page : Int?, pageSize : Int?, requestParam : String?){
        try {
            viewModelScope.launch {
                val response = repository.getAllBooksOrderByBorrowNum(page, pageSize, requestParam)
                if (response.code == 1) {
                    if (page == 1){
                        _bookList.postValue(response.data?.rows)
                    }else{
                        val currentList = _bookList.value ?: mutableListOf()
                        // 仅追加新获取的 21 条数据
                        response.data?.rows?.let { newList ->
                            currentList.addAll(newList)
                            _bookList.postValue(currentList)
                        }
                    }
                    _total.value = response.data?.total!!.toLong() ?: 0L
                    _toastMessage.postValue(EventUtil("库存信息获取成功"))
//                    _toastMessage.postValue(EventUtil(total.value.toString()))
                } else {
                    _bookList.postValue(null)
                    _total.postValue(0L)
                    _toastMessage.postValue(EventUtil("库存信息获取失败，请检查网络"))
                }
            }
        } catch (e: Exception) {
            e.printStackTrace()
        }
    }

    /**
     * 借阅图书
     */
    fun borrowBook(userId: Long, bookId: Int) {
        viewModelScope.launch {
            val res = repository.borrowBook(userId, bookId)
            _borrowResponse.value = res
            // 如果借阅成功，可以提示用户并更新 UI（例如刷新图书列表）
            if (res.code == 1) {
                fetchBorrowedBooks(CurrentLoginInfo.getCurrentLoginInfo()!!.id.toLong())
                _toastMessage.postValue(EventUtil("借阅成功"))
            } else {
                _toastMessage.postValue(EventUtil(res.msg))
            }
        }
    }

    /**
     * 根据用户ID查询借阅图书
     */
    fun fetchBorrowedBooks(userId: Long) {
        viewModelScope.launch {
            try {
                val res: Res<List<Book>> = repository.getBorrowedBooks(userId)
                if (res.code == 1) {
                    _borrowedBooks.postValue(res.data ?: emptyList())
                    _toastMessage.postValue(EventUtil("查询成功"))
                } else {
                    _borrowedBooks.postValue(emptyList())
                    _toastMessage.postValue(EventUtil("查询失败：" + res.msg))
                }
            } catch (e: Exception) {
                e.printStackTrace()
                _toastMessage.postValue(EventUtil("网络错误：123" + e.message))
            }
        }
    }

    /**
     * 调用还书接口
     */
    fun returnBook(userId: Long, bookId: Int) {
        viewModelScope.launch {
            val res = repository.returnBook(userId, bookId)
            _returnResponse.value = res
            if (res.code == 1) {
                // 成功提示（也可以通知刷新列表等操作）
                 _toastMessage.postValue(EventUtil("还书成功"))
            } else {
                // 失败提示
                 _toastMessage.postValue(EventUtil(res.msg))
            }
        }
    }

    fun borrowBookByQrcode(userId: Long, bookIsbn: String) {
        viewModelScope.launch {
            try {
                val res = repository.borrowBookByQrcode(userId, bookIsbn)
                _qrcodeResponse.value = res
                if (res.code == 1) {
                    // 成功提示（也可以通知刷新列表等操作）
                    _toastMessage.postValue(EventUtil("借阅成功"))
                } else {
                    // 失败提示
                    _toastMessage.postValue(EventUtil(res.msg))
                }
            } catch (e: Exception) {
                e.printStackTrace()
            }
        }
    }

    fun fetchAllBorrowedBooks(userId: Long) {
        viewModelScope.launch {
            try {
                val res: Res<List<Book>> = repository.getAllBorrowedBooks(userId)
                if (res.code == 1) {
                    _allBorrowedBooks.value = res.data ?: emptyList()
                    _toastMessage.value = EventUtil("查询成功")
                } else {
                    _allBorrowedBooks.value = emptyList()
                }
            }catch (e: Exception){
                e.printStackTrace()
                _toastMessage.value = EventUtil("查询失败：" + e.message)
            }
        }
    }

    fun fetchAllReturnedBooks(userId: Long) {
        viewModelScope.launch {
            try {
                val res: Res<List<Book>> = repository.getAllReturnedBooks(userId)
                if (res.code == 1) {
                    _allReturnedBooks.value = res.data ?: emptyList()
                    _toastMessage.value = EventUtil("查询成功")
                } else {
                    _allReturnedBooks.value = emptyList()
               }
            }catch (e: Exception){
                e.printStackTrace()
            }
        }
    }


}